﻿#include"XQFileThread.h"
#include<QDateTime>
#include<QDebug>
std::atomic<int> XQFileThread::m_tasksCount = 0;
XQFileThread::XQFileThread(const QString& name, QThreadPool* pool)
	:QFile(name)
{
	setThreadPool(pool);
	init();
}

XQFileThread::~XQFileThread()
{
	if (m_buffer != nullptr)
		delete[]m_buffer;
	if (m_startTime != nullptr)
		delete m_startTime;
}

size_t XQFileThread::bufferSize()const
{
	return m_bufferSize;
}

QThreadPool* XQFileThread::threadPool()const
{
	return m_pool;
}

size_t XQFileThread::progressSignalsTime()const
{
	return m_progressSignalsTime;
}

QString XQFileThread::newName() const
{
	QString name = m_newName;
	return name;
}

int XQFileThread::tasksCount() const
{
	return m_tasksCount;
}

void XQFileThread::setBufferSize(const size_t size)
{
	if (m_buffer != nullptr)
		delete[]m_buffer;
	m_buffer = new char[m_bufferSize];
	if (m_buffer == nullptr)//申请内存失败
	{
		m_bufferSize = 0;
		qWarning() << "XQFileThread::setBufferSize 申请缓冲区失败";
		return;
	}
		m_bufferSize = size;
}

void XQFileThread::copy(const QString& newName)
{
	m_newName = newName;
	auto func = std::bind(&XQFileThread::_copy, this, newName);
	m_pool->start(func);//加入线程池
}

void XQFileThread::setProgressSignalsTime(size_t time)
{
	m_progressSignalsTime = time;
}

void XQFileThread::init()
{
	//connect(this, &XQFileThread::copyFinish, this, &XQFileThread::deleteLater);//结束时释放自己
	m_buffer = new char[BUFFERSIZE];//初始化缓冲区
	m_bufferSize = BUFFERSIZE;
}

void XQFileThread::_copy(const QString& newName)
{
	//只读打开
	if (!open(QIODeviceBase::OpenModeFlag::ReadOnly))
		return ;
	QFile newFile(newName);
	//新文件写打开
	if (!newFile.open(QIODeviceBase::OpenModeFlag::WriteOnly))
		return ;
	if (m_startTime == nullptr)
		m_startTime = new QDateTime();
	*m_startTime= QDateTime::currentDateTime();
	m_tasksCount++;
	size_t readSize = 0;//读取的字节
	size_t sumSize = 0;//总大小
	emit copyStart(fileName(), newName,size());
	while (!atEnd())
	{
		readSize = read(m_buffer, m_bufferSize);
		newFile.write(m_buffer, readSize);
		sumSize += readSize;
		sendCopyProgress( newName, sumSize);
	}
	m_tasksCount--;
	emit copyFinish(fileName(), newName, size());
}

void XQFileThread::sendCopyProgress(const QString& newName, size_t sumSize)
{
	QDateTime endTime = QDateTime::currentDateTime();
	if (m_startTime->msecsTo(endTime) > m_progressSignalsTime)
	{
		emit copyProgress(fileName(), newName, sumSize, size());//时间到了发送信号
		//qInfo() << "发送信号" << sumSize;
		*m_startTime = endTime;
	}
}

void XQFileThread::setThreadPool(QThreadPool* pool)
{
	m_pool = pool;
}
